package top.v5it.japi.plus.core.exception;

import cn.hutool.core.util.StrUtil;
import lombok.Getter;
import top.v5it.japi.plus.core.api.ResultStatus;
import top.v5it.japi.plus.core.api.ResultStatusTemplate;

import java.util.Objects;


/**
 * 框架错误
 *
 * @author zhanpu
 */
@Getter
public class JapiException extends RuntimeException {

    private final ResultStatusTemplate resultStatusTemplate;

    public JapiException() {
        this(ResultStatus.SYSTEM_ERROR);
    }

    public JapiException(ResultStatusTemplate resultStatusTemplate) {
        super();
        this.resultStatusTemplate = resultStatusTemplate;
    }

    public JapiException(ResultStatusTemplate resultStatusTemplate, String messageTemplate, Object... params) {
        super(StrUtil.format(messageTemplate, params));
        this.resultStatusTemplate = resultStatusTemplate;
    }

    public JapiException(ResultStatusTemplate resultStatusTemplate, Throwable cause, String messageTemplate, Object... params) {
        super(StrUtil.format(messageTemplate, params), cause);
        this.resultStatusTemplate = resultStatusTemplate;
    }

    public JapiException(ResultStatusTemplate resultStatusTemplate, Throwable cause) {
        super(cause);
        this.resultStatusTemplate = resultStatusTemplate;
    }

    public static JapiException of(Exception ex) {
        return Objects.nonNull(ex)
                ? (JapiException) ex
                : new JapiException(ResultStatus.SYSTEM_ERROR);
    }

    public boolean causeInstanceOf(Class<? extends Throwable> clazz) {
        final Throwable cause = this.getCause();
        return Objects.nonNull(cause) && clazz.isInstance(cause);
    }
}
